﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Drawing.Drawing2D;
using BusinessLogic;
using BusinessObject;
using Utility;
using System.Web.Security;
using System.Resources;
namespace WebTeamplate
{

    public partial class Admin_ViewPhieuBanHang : BasePage
    {
        public string nguoiLapPhieu = string.Empty;
        public string kho = string.Empty;
        public string CurencyName = string.Empty;
        public PhieuBanHang objPhieuBanHang = new PhieuBanHang();
        public KhachHang objKhachHang = new KhachHang();
        public Curency objCurencyDefault = new Curency();
        public string MaSoPhieu = string.Empty;
        public Int64 MaPhieuBan
        {

            get
            {
                object o = ViewState["MaPhieuBan"];
                if (o != null) return (Int64)o;
                return Int64.MinValue;
            }

            set { ViewState["MaPhieuBan"] = value; }

        }
        #region Init,Load
        protected void Page_Load(object sender, EventArgs e)
        {         
            if (!Page.IsPostBack)
            {
                InitParamater();
            }
            LoadData();
        }
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
        }
        private void InitParamater()
        {
            MaPhieuBan = ConvertValueObject.ParseLong(CommonFunction.GetValueFromQueryString(this.Page, "id"));
        }
        #endregion

        #region Methods
        double total = 0;
        public void LoadData()
        {
            objPhieuBanHang = PhieuBanHangUtil.Get(this.MaPhieuBan);
            if (objPhieuBanHang != null)
            {
                if (objPhieuBanHang.IsCommit)
                    btnEdit.Visible = false;
                else
                    btnEdit.Visible = true;
                MaSoPhieu = objPhieuBanHang.MaSoPhieu;
                objCurencyDefault = PhieuBanHangUtil.GetCurencyForPhieuBanHang(this.MaPhieuBan);
                MembershipUser member = Membership.GetUser(objPhieuBanHang.NguoiLapPhieu);
                if (member != null)
                {
                    UserProfile objProfile = UserProfileUtil.Get(this.applicationName, new Guid(member.ProviderUserKey.ToString()));
                    if (objProfile != null)
                        nguoiLapPhieu = objProfile.Name;
                    else nguoiLapPhieu = objPhieuBanHang.NguoiLapPhieu;
                }
                else nguoiLapPhieu = objPhieuBanHang.NguoiLapPhieu;
                //get Kho
                SubCategory objKho = SubCategoryUtil.Get(objPhieuBanHang.MaKho, CommonFunction.DEFAULT_WAREHOUSE_CODE);
                kho = objKho.SubCategoryName;
                //get KH
                objKhachHang = KhachHangUtil.Get(objPhieuBanHang.MaKhachHang);
                if (objPhieuBanHang == null)
                    objPhieuBanHang = new PhieuBanHang();
                //get List Data
                List<ChiTietPhieuBanHangDetail> lstChiTiet = PhieuBanHangUtil.GetChiTietPhieuBanHangDetailByMaPhieuBanHang(this.MaPhieuBan);
                //generate form here
                rptData.DataSource = lstChiTiet;
                rptData.DataBind();
              //  Literal ltrTotal= (Literal)rptData.TemplateControl.FindControl("ltrTotal");
              //  ltrTotal.Text = ConvertValueObject.ParseString(total);
                double VAT = 1;
                if (objPhieuBanHang.IsVAT)
                {
                    VAT = objPhieuBanHang.VAT;
                }
                ltrTotalString.Text = CommonFunction.ReadNumber(ConvertValueObject.ParseString(total*VAT)) + " " + objCurencyDefault.Name;

            }
        }

        #endregion

        #region Events,Handler

        protected void rptData_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                ChiTietPhieuBanHangDetail cate = (ChiTietPhieuBanHangDetail)e.Item.DataItem;
                if (cate == null)
                    return;
                Literal ltr = (Literal)e.Item.FindControl("ltrGia");
                ltr.Text = ConvertValueObject.ParseString(cate.GiaBan) + " " + objCurencyDefault.Name;

                ltr = (Literal)e.Item.FindControl("ltrSTT");
                ltr.Text = (e.Item.ItemIndex + 1).ToString();
                ltr = (Literal)e.Item.FindControl("ltrThanhTien");
                double thanhtien = cate.SoLuongBan * cate.GiaBan;
                ltr.Text = ConvertValueObject.ParseString(thanhtien) + " " + objCurencyDefault.Name;               

                total +=thanhtien;
            }
            else if (e.Item.ItemType ==ListItemType.Footer)
            {
                Literal ltr = (Literal)e.Item.FindControl("ltrTotal");
                ltr.Text = ConvertValueObject.ParseString(total) + " " + objCurencyDefault.Name;

                ltr = (Literal)e.Item.FindControl("ltrTotalVAT");
                ltr.Text = ConvertValueObject.ParseString(total*objPhieuBanHang.VAT) + " " + objCurencyDefault.Name;

            }
        }

        #endregion

        protected void btnEdit_Click(object sender, EventArgs e)
        {
            Response.Redirect("ChiTietPhieuBanHang.aspx?id=" + this.MaPhieuBan + "&act=edit");
        }
        
        protected void btnCancel_Click(object sender, EventArgs e)
        {
            Response.Redirect("DMPhieuBanHang.aspx");
        }
        protected void btnExportExcel_Click(object sender, EventArgs e)
        {
            List<ChiTietPhieuBanHangDetail> lstChiTiet = PhieuBanHangUtil.GetChiTietPhieuBanHangDetailByMaPhieuBanHang(this.MaPhieuBan);
            ExportExcel(string.Empty, "Phiếu báo giá", lstChiTiet);
        }
        public void ExportExcel(string strPathOut, string pageTitle, List<ChiTietPhieuBanHangDetail> lstData)
        {
            try
            {
                //Export
                // int columnCount = 8;// dgvSource.ColumnCount;
                string result = string.Empty;
                //Create page Infor
                result += "<?xml version='1.0' encoding='UTF-8'?>\r\n";
                result += "<?mso-application progid='Excel.Sheet'?>\r\n";
                result += "<Workbook xmlns='urn:schemas-microsoft-com:office:spreadsheet'\r\n";
                result += " xmlns:o='urn:schemas-microsoft-com:office:office'\r\n";
                result += " xmlns:x='urn:schemas-microsoft-com:office:excel'\r\n";
                result += " xmlns:ss='urn:schemas-microsoft-com:office:spreadsheet'\r\n";
                result += " xmlns:html='http://www.w3.org/TR/REC-html40'>\r\n";
                result += " <ExcelWorkbook xmlns='urn:schemas-microsoft-com:office:excel'></ExcelWorkbook>\r\n";
                //Create Page Style Sheet
                result += "   <Styles>\r\n";
                result += "       <Style ss:ID='PageTitle'>\r\n";
                result += "           <Alignment ss:Horizontal='Center' ss:Vertical='Center'/>\r\n";
                result += ExcelUtil.CreateCellBorder();
                result += "           <Font ss:FontName='Calibri' x:Family='Swiss' ss:Size='14' ss:Color='#000000'    ss:Bold='1'/>\r\n";
                result += "       </Style>\r\n";

                result += "       <Style ss:ID='total'>\r\n";
                result += "           <Alignment ss:Horizontal='Right' ss:Vertical='Center'/>\r\n";
                result += ExcelUtil.CreateCellBorder();
                result += "           <Font ss:FontName='Calibri' x:Family='Swiss' ss:Size='14' ss:Color='#000000'    ss:Bold='1'/>\r\n";
                result += "       </Style>\r\n";

                result += "       <Style ss:ID='pageHeader'>\r\n";
                result += "         <Alignment ss:Horizontal='Center' ss:Vertical='Center'/>\r\n";
                result += ExcelUtil.CreateCellBorder();
                result += "           <Font ss:FontName='Calibri' x:Family='Swiss' ss:Size='11' ss:Color='#000000' ss:Bold='1'/>\r\n";
                result += "         <Interior ss:Color='#BFBFBF' ss:Pattern='Solid'/>\r\n";
                result += "       </Style>\r\n";
                result += "      <Style ss:ID='data'>\r\n";
                result += ExcelUtil.CreateCellBorder();
                result += "       </Style>\r\n";
                result += "   </Styles>\r\n";
                //Create table  
                result += "   <Worksheet ss:Name='" + pageTitle + "'>\r\n";
                result += "       <Table  ss:DefaultRowHeight='15'>\r\n";
                result += "<Column ss:AutoFitWidth='0' ss:Width='30'/>";
                result += "  <Column ss:AutoFitWidth='0' ss:Width='80'/>";
                result += "  <Column ss:AutoFitWidth='0' ss:Width='200'/>";
                result += "  <Column ss:AutoFitWidth='0' ss:Width='100'/>";
                result += "  <Column ss:AutoFitWidth='0' ss:Width='120'/>";
                result += "  <Column ss:AutoFitWidth='0' ss:Width='60'/>";
                result += "  <Column ss:AutoFitWidth='0' ss:Width='80'/>";
                result += "  <Column ss:AutoFitWidth='0' ss:Width='70'/>";
                result += "           <Row ss:AutoFitHeight='0' ss:Height='19.5'>\r\n";
                result += "               <Cell ss:MergeAcross='7' ss:StyleID='PageTitle'><Data ss:Type='String'>" + pageTitle + "</Data></Cell>\r\n";
                result += "           </Row>\r\n";
                //Create Gird Header
                result += "           <Row ss:AutoFitHeight='0'>\r\n";

                result += "     <Cell ss:StyleID='pageHeader'><Data ss:Type='String'>STT</Data></Cell>\r\n";
                result += "     <Cell ss:StyleID='pageHeader'><Data ss:Type='String'>Mã MH</Data></Cell>\r\n";
                result += "     <Cell ss:StyleID='pageHeader'><Data ss:Type='String'>Tên MH</Data></Cell>\r\n";
                result += "     <Cell ss:StyleID='pageHeader'><Data ss:Type='String'>Nước SX</Data></Cell>\r\n";
                result += "     <Cell ss:StyleID='pageHeader'><Data ss:Type='String'>Hiệu</Data></Cell>\r\n";
                result += "     <Cell ss:StyleID='pageHeader'><Data ss:Type='String'>Số lượng</Data></Cell>\r\n";
                result += "     <Cell ss:StyleID='pageHeader'><Data ss:Type='String'>Đơn vị tính</Data></Cell>\r\n";
                result += "     <Cell ss:StyleID='pageHeader'><Data ss:Type='String'>Giá nhập</Data></Cell>\r\n";

                // string columnWidth = "  <Column ss:AutoFitWidth='0' ss:Width='100'/>\r\n";

                result += "         </Row>\r\n";
                //Export Data                
                int rowCount = lstData.Count;
                double total = 0;
                for (int j = 0; j < rowCount; j++)
                {
                    ChiTietPhieuBanHangDetail objData = lstData[j];
                    result += " <Row ss:AutoFitHeight='0'>\r\n";
                    result += "<Cell ss:StyleID='data'><Data ss:Type='Number'>" + (j + 1).ToString() + "</Data></Cell>\r\n";
                    result += "<Cell ss:StyleID='data'><Data ss:Type='String'>" + objData.MaMatHang + "</Data></Cell>\r\n";
                    result += "<Cell ss:StyleID='data'><Data ss:Type='String'>" + objData.TenMatHang + "</Data></Cell>\r\n";
                    result += "<Cell ss:StyleID='data'><Data ss:Type='String'>" + objData.NuocSX + "</Data></Cell>\r\n";
                    result += "<Cell ss:StyleID='data'><Data ss:Type='String'>" + objData.Hieu + "</Data></Cell>\r\n";
                    result += "<Cell ss:StyleID='data'><Data ss:Type='Number'>" + objData.SoLuongBan + "</Data></Cell>\r\n";
                    result += "<Cell ss:StyleID='data'><Data ss:Type='String'>" + objData.DonViTinh + "</Data></Cell>\r\n";
                    result += "<Cell ss:StyleID='data'><Data ss:Type='Number'>" + objData.GiaBan + "</Data></Cell>\r\n";
                    total += objData.GiaBan;
                    //for (int k = 0; k < columnCount; k++)
                    //{
                    //    string value = lstData[
                    //    result += "<Cell ss:StyleID='data'><Data ss:Type='String'>" + value + "</Data></Cell>\r\n";

                    //}
                    result += " </Row>\r\n";

                }
                result += "           <Row ss:AutoFitHeight='0' ss:Height='19.5'>\r\n";
                result += "               <Cell ss:MergeAcross='6' ss:StyleID='total'><Data ss:Type='String' >Thành tiền</Data></Cell>\r\n";
                result += "               <Cell ss:StyleID='data'><Data ss:Type='Number'>" + total + "</Data></Cell>\r\n";
                result += "           </Row>\r\n";

                result += "       </Table>";
                result += "   </Worksheet>";
                result += "</Workbook>";
                //result = string.Format(result, columnWidth);

                //StreamWriter strwriter = new StreamWriter(strPathOut);
                //strwriter.WriteLine(result.ToString());
                //strwriter.Close();
                Response.Cache.SetExpires(DateTime.Now.AddSeconds(1));
                Response.Clear();
                string strExten = ".xls";
                string strType = "application/vnd.ms-excel";
                //Response.AppendHeader("content-disposition", "attachment;filename=" + filename);
                Response.AppendHeader("content-disposition", "attachment;filename=phieuBaoGia.xls");
                Response.Charset = "UTF-8";
                Response.Cache.SetCacheability(HttpCacheability.NoCache);
                //Response.ContentType = "application/vnd.ms-excel";
                //Response.ContentType = "application/vnd.ms-word";
                Response.ContentType = strType;
                this.EnableViewState = false;
                Response.Write("\r\n");
                Response.Write(result);
                Response.End();
            }
            catch
            { }
        }
        public string GetXe(string maxe)
        {
            DMXe objXe = DMXeUtil.Get(ConvertValueObject.ParseInt(maxe));
            if (objXe != null)
                return objXe.TenXe;
            else return string.Empty;
        }
    }
}
